# vector(0, 0.0006 * sin( 2*pi*2500000000.0*t ) + 0.0006 * sin( 2*pi*2550000000.0*t ) ,0.01)
import class_sim as sim
import numpy as np
from matplotlib import pyplot as plt
from multiprocessing import Pool,Process
from ndemag import setNdemag
def N(name,n,dx):
    #并行计算退磁张量
    n_demag = np.zeros([2*i-1 for i in n] + [6,])
    results=[]
    p=Pool(6)
    for i, per_fun in enumerate(((0,1,2),(0,1,2),(0,2,1),(1,2,0),(1,2,0),(2,0,1))):
        result_=p.apply_async(func=setNdemag,args=(i,list(per_fun),list(n),list(dx),n_demag ,))
        results.append(result_)
    p.close()
    p.join()
    for i in range(6):
        n_demag[:,:,:,i]=results[i].get()
    np.save(str(name)+"_ndemag"+".npy",n_demag)
#================================================================
if __name__=="__main__":
    name="YIG0"
    mu0=4e-7 * np.pi
    n=[40,40,40]
    dx=[10e-9,10e-9,10e-9]
    # N(name=name,n=n,dx=dx)#计算退磁张量

#=======relax==========================================================
    sim.sim(
    name=name,
    namedemag="YIG_ndemag",
    n=n,
    dx=dx,
    m0=[0,0.1,1],
    gamma = 2.211e5,
    ms    = 140e3,
    A     = 3.5e-12,
    alpha=1,
    h_zee=lambda t:[0,0, 0.06/mu0],
    T=2e-9,
    T0=0,
    fixdt=1e-12,
    inscribed=True).run()

# #=======run========================================================
    for i in range (1):
        m0=np.load(str(name)+"SIMnow"+".npy")
        name="YIG"+str(i)
        p1 =Process(target=sim.sim(
        name=name,
        namedemag="YIG_ndemag",
        n=n,
        dx=dx,
        m0=m0,
        gamma = 2.211e5,
        ms    = 140e3,
        A     = 3.5e-12,
        alpha=0.009331784829954797,
        h_zee=lambda t:[0,( 0.0006 * np.sin( 2*np.pi*2500000000.0*t ) + 0.0006 * np.sin( 2*np.pi*2550000000.0*t ))/mu0 ,0.06/mu0],
        T=1e-8*(i+1), 
        T0=1e-8*i,
        fixdt=1e-12,
        inscribed=True).run(),) 
        p1.start()
        p1.join()
#======visual=========================================================
    Y=np.load(str(name)+"SIM"+".npy")
    R=np.load(str(name)+"SIM"+"error.npy",allow_pickle=True)
    m_avg=Y
    plt.subplot(1, 2, 2)
    plt.plot(m_avg[:,0], m_avg[:,1]) 
    plt.plot(m_avg[:,0], m_avg[:,2])
    plt.plot(m_avg[:,0], m_avg[:,3])

    plt.xlabel("Time (ns)")
    plt.ylabel("Magnetization")
    plt.title("m")

    plt.subplot(1, 2, 1)
    plt.plot(range(len(R)),R)

    plt.xlabel("step")
    plt.ylabel("err")
    plt.title("r")

    plt.show()
    input()